package Servlet;

import Utils.DbUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/UpdataServlet")
public class UpdataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String tableName = req.getParameter("tableName");
        String[] columns = req.getParameterValues("column");
        String[] oldColumn = req.getParameterValues("oldColumn");
        String tablename = req.getParameter("tablename");
        String sql = "UPDATE " + tablename + " SET ";
        Object[] row = new Object[oldColumn.length + columns.length];
        Map<String, String> map = DbUtil.getColumnAndType(req, tablename);
        map.forEach((key, value) -> {
            System.out.println(key + " = " + value);
        });
        int count = 0;
        for (int i = 0; i < columns.length; i++) {
            if (map.get(columns[i]).equals("INT")) {
                row[i] = Integer.parseInt(req.getParameter(columns[i]));
            } else if (map.get(columns[i]).equals("VARCHAR") || map.get(columns[i]).equals("CHAR")) {
                row[i] = req.getParameter(columns[i]);
            } else if (map.get(columns[i]).equals("DOUBLE")) {
                row[i] = Double.parseDouble(req.getParameter(columns[i]));
            } else if (map.get(columns[i]).equals("FLOAT")) {
                if (!req.getParameter(columns[i]).isEmpty()) { // 如果为空字符串，不会执行{}中的语句
                    row[i] = Float.parseFloat(req.getParameter(columns[i]));
                } else row[i] = null;
            } else {
                try {
                    throw new Exception("暂时不支持数据类型修改");
                } catch (Exception e) {
                    req.setAttribute("error", e.getMessage());
                    RequestDispatcher rd = req.getRequestDispatcher("error.jsp");
                    rd.forward(req, resp);
                }
            }

            if (value == null) {
                sqlBuilder.append(column).append(" is NULL");
            } else {
                sqlBuilder.append(column).append(" = ?");
                params.add(value);
            }

            if (++count < columns.length) {
                sqlBuilder.append(", ");
            }
        }

        sqlBuilder.append(" WHERE ");
        count = 0;
        sql += " where ";
        for (int i = 0; i < columns.length; i++) {
            if (map.get(columns[i]).equals("INT")) {
                row[columns.length + i] = Integer.parseInt(req.getParameter(oldColumn[i] + "_old"));
            } else if (map.get(columns[i]).equals("VARCHAR") || map.get(columns[i]).equals("CHAR")) {
                row[columns.length + i] = req.getParameter(oldColumn[i] + "_old");
            } else if (map.get(columns[i]).equals("DOUBLE")) {
                row[columns.length + i] = Double.parseDouble(req.getParameter(oldColumn[i] + "_old"));
            } else if (map.get(columns[i]).equals("FLOAT")) {
                if (!req.getParameter(oldColumn[i] + "_old").isEmpty()) { // 如果为空字符串，不会执行{}中的语句
                    row[columns.length + i] = Float.parseFloat(req.getParameter(oldColumn[i] + "_old"));
                } else row[columns.length + i] = null;
            } else {
                try {
                    throw new Exception("暂时不支持数据类型修改");
                } catch (Exception e) {
                    req.setAttribute("error", e.getMessage());
                    RequestDispatcher rd = req.getRequestDispatcher("error.jsp");
                    rd.forward(req, resp);
                }
            }
            sql += oldColumn[i] + "= ?";
            if (++count < oldColumn.length) { // 判断是否为最后一个元素
                sql += " and "; // 如果不是最后一个，则输出逗号分隔符
            }
        }
        System.out.println(sql);
        for (int j = 0; j < row.length; j++) {
            if (row[j] == null) {
                System.out.println("null");
            } else {
                System.out.println(row[j]);
            }

            if (++count < oldColumns.length) {
                sqlBuilder.append(" AND ");
            }
        }
        DbUtil.executeUpdate(req, resp, sql, row);
        resp.sendRedirect("GetAllTableServlet");
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
